package ohos.histreamer.demo;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class PlayList {
    private static final String TAG = "HST_PlayList";

    private final String directory;
    private final MainActivity mainActivity;

    private ArrayList<String> avlist;
    private int selected;
    private AlertDialog alertDialog;

    public PlayList(String dir, MainActivity activity) {
        directory = dir;
        mainActivity = activity;
        avlist = listFiles(directory);
        alertDialog = new AlertDialog.Builder(activity)
                .setTitle("当前播放")
                .setItems(avlist.toArray(new CharSequence[avlist.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selected = which;
                        mainActivity.play(directory + File.separator + avlist.get(which));
                    }
                })
                .create();
        Log.d(TAG, "play list directory: " + directory);
    }

    public void show() {
        alertDialog.show();
    }

    public String getSelectedFilename() {
        return directory + File.separator + avlist.get(selected);
    }

    public String getNextFilename(){
        if (selected == avlist.size()) {
            Log.d(TAG, "start again.");
            selected = 0;
        } else {
            selected++;
        }
        return directory + File.separator + avlist.get(selected);
    }

    private ArrayList<String> listFiles(String dir) {
        Set<String> fileList = new HashSet<>();
        try {
            DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(dir));
            for (Path path : stream) {
                if (!Files.isDirectory(path)) {
                    fileList.add(path.getFileName().toString());
                    Log.d(TAG, "Add new song: " + path.toString());
                }
            }
        } catch (IOException ex) {
            Log.d(TAG, "listFiles exception:");
            ex.printStackTrace();
        }
        return new ArrayList<String>(fileList);
    }
}
